<?php
/**
 * 腾讯读书蜘蛛
 * netxlong
 * 
 */

if (!empty($_POST['url'])) {
    $url = $_POST['url']; //书地址
    $file = "book.txt";
    $content = file_get_contents($url);
    $content = iconv('GBK', 'UTF-8//IGNORE', $content);
    $preg_title = "/<td><div><a href=\"javascript:opennew\(\'(.*?)\'\)\".?>(.*?)<\/a>/is"; //匹配title
    $preg_content = "/<div id=\"content\"(.*?)\">(.*?)<\/div>/is"; //匹配主题内容 
    
    file_put_contents($file, '');
    preg_match_all($preg_title, $content, $title);
    $title_urls = $title[1];
    $title_content = $title[2];
    $i = 0;
    foreach ($title_urls as $title_url) {
        require_once("HTTP/Request.php");
        $req = new HTTP_Request($title_url);
        $req->setMethod(HTTP_REQUEST_METHOD_GET);
        $req->addHeader("Date", date(DATE_RFC822));
        $req->addHeader("Vary", "Host,Accept-Encoding");
        $req->addHeader("Content-Encoding", "gzip");
        $req->addHeader("Referer", $url);
        $req->addHeader("Connection", "close");
        if (!PEAR::isError($req->sendRequest())) {
        		 $response = $req->getResponseBody();
        } else {
        		 $response = '';
        		 die('fail fetch list');
        }
        $response = iconv('GBK', 'UTF-8//IGNORE', $response);
        preg_match($preg_content, $response ,$article_content);
        $ctent = str_replace('<br />', "\n", $article_content[2]);
        $last_content = $title_content[$i].$ctent;
        $article .= $last_content;
        $i++;
    }
    
    file_put_contents($file, $article, FILE_APPEND);
    header('Content-type: text/plain');//输出的类型
    header('Content-Disposition: attachment; filename='.$file);
    echo file_get_contents($file);
}
?>
